<template>
  <view>
    <card-dial v-if="mantles && mantles.length" :list="mantles" title="维保责任人"
					:imgSrc="require('@/static/images/index/sign.png')"></card-dial>
	<view class="text_tit">该电梯下所有已计划的且未完成的保养任务</view>
    <view>
        <view class="tabMonth">
            <view class="tabMonth_M">
                <view class="filterBox">
                    <view :class="['typeItem', typeIndex == 1 ? 'act' : '']" @click="changeTypes(1)"
                        :style="{ borderRight: typeIndex == 2 ? 'none' : '' }">
                        <image class="ico" src="@/static/images/repairFitting/signMonth.png"
                            v-if="typeIndex == 1" mode=""></image>
                        <image class="ico" src="@/static/images/repairFitting/signMonthR.png" v-else mode="">
                        </image>
                        月历视图
                    </view>
                    <view :class="['typeItem', typeIndex == 2 ? 'act actRight' : '']" @click="changeTypes(2)">
                        <image class="ico" src="@/static/images/repairFitting/list2.png" v-if="typeIndex == 2"
                            mode=""></image>
                        <image class="ico" src="@/static/images/repairFitting/list1.png" v-else mode=""></image>
                        列表视图
                    </view>
                </view>
            </view>
            <view class="tab_down" @click="selectDown" v-if="typeIndex == 1">
                <image src="@/static/images/download.png" style="width: 32rpx;height: 32rpx;" alt="" srcset=""
                    mode="" />
                <text>下载计划</text>
            </view>
        </view>
        <!-- 日历组件 -->
        <view class="todayPlus"
            :style="typeIndex === 1 ? 'display:block' : 'display:none'">
            <view class="today" @click="todayClick">
                <image src="@/static/images/index/today.png" mode=""></image>
                <text>今天</text>
            </view>
            <monthPlanCom ref="monthPlanCom" :isSinEle="true" :mheight="mheights" :monthArrs="monthArrs"
                @select="selectTime" @loadScrollMonth="loadScrollMonth" />
        </view>
        <!-- 列表组件 -->
        <block v-if="typeIndex == 2">
				<view class="tabBox">
					<!-- 任务安排提示 -->
					<view class="orderTips">
						<view>{{ title }}</view>
						<!-- <view>列表视图仅显示未完成保养任务及未来半年内保养计划</view> -->

					</view>
					<!-- 列表 -->
					<view class="orderListMain">
						<view class="" v-if="list.length">
							<view class="content" v-for="(item, index) in list" :key="index">
								<view class="date">
									{{ item.planDate }}
									<view class="line"></view>
								</view>
								<view>
									<order-list v-for="(e, i) in item.dataList" :key="i" :item="e" :tabIdx="tabIdx"
										:typeIdx="1" :parentIdx="index" :childIdx="i" @userMore="handleUserMore"
										:elevatorId="elevatorId" @update="restList()">
									</order-list>
								</view>
							</view>
							<view class="more">- 已经到底了 -</view>
						</view>

						<view class="empty" v-else>
							<view class="img">
								<image src="@/static/images/default.png"></image>
							</view>
							<view class="text">- 暂无相关数据 -</view>
						</view>
					</view>
				</view>

			</block>
    </view>

    <!-- 筛选组件 -->
    <filter-drawer :chooseData="choosed" :filterList="filterList" :comfireText="comfireText" :show="showFilter"
        :keyMap="keyMap" title="保养计划下载设置" mainTips="(请选择需要查看保养计划的时间范围)" ref="filter-drawer" :dateLists="dateLists"
        :orderType="orderType" :isMainPlan="true" :isFilterList="eleMsg" :countState="countState"
        :isShowDate="false" @closed="handleClose" @submit="submitFilter" @chooseTag="getResultCount"
        @defaultReset="defaultReset" @customerOpenTime="customerOpenTime"></filter-drawer>
    <!-- 完成时间 -->
    <time-select v-if="selectTimePopup" :beforeToday="beforeToday" :atterToday="true" :isChooseToday="isChooseToday"
        @close="closeSelectTimePopup"></time-select>
    <!-- 下载成功对话框 -->
    <model width="508rpx" :visible="successVisible" title="成功导出保养计划" cancleTxt="复制链接" comfireTxt="直接打开"
        @cancle="copyLink" @comfire="openFile">
        <view class="conte">
            <view class="modelItem"> 你可以直接打开，或者复制链接至 </view>
            <view class="modelItem"> 电脑端浏览器下载。 </view>
        </view>
    </model>

  </view>
</template>

<script>
import cardDial from '@/components/card-dial/card-dial.vue';
import monthPlanCom from '@/components/dateSelect/monthPlanCom.vue';
import OrderList from './eleOrderList.vue';
// import filterModel from './components/filter/index.vue';
import filterDrawer from '@/components/filter-drawer/filterDrawer.vue';
import model from '@/components/model/index.vue';
import timeSelect from '@/pages/index/components/timeSelect.vue';

import { calendarPlan, calendarPlanExcel, calendarStatisticsCount } from '@/apis/maintains.js';
import { elevtorDetail, elevtorMantles,maintenanceUnfinished } from '@/apis/elevator.js';
import dayjs from 'dayjs';
import { removeEmpty, getNowTime } from '@/utils/utils.js';
export default {
	components:{
		cardDial,
		monthPlanCom,
		OrderList,
		filterDrawer,
		// filterModel,
		model,
		timeSelect
	},
	data() {
		return {
			// elevatorId:"1614082203923881986",
			mantles: [], // 电梯责任人
			eleMsg:{},
			typeIndex:1,
			monthArrs: {},// 月历数据
			strTimes:'',
			startDate:'',
			endDate:'',
			tabIdx:0,
			list:[],// 列表数据
			title:'',
			// 筛选组件
			tempFilePath: '',
			excelURl: '',
			countState: 0,
			curValue: 0,// 计划时间的value值
			curStartDate: '',// 自定义日期
			curEndDate: '',// 自定义日期
			mheights: 0,
			// 筛选组件
			showFilter: false,
			comfireText: '确定',
			allChecked: true,
			orderType: 0,
			choosed: {},
			chooseArr: [],
			filterList: [],
			keyMap: {},
			dateLists: [
				{ name: '今天', value: 1 },
				{ name: '本周', value: 2 },
				{ name: '本月', value: 3 },
				{ name: '后1个自然月', value: 4 },
				{ name: '后2个自然月', value: 5 },
				{ name: '后3个自然月', value: 6 },
			],
			// 日期组件
			selectTimePopup: false,
			successVisible: false,
			beforeToday: true,// 日期组件
			isChooseToday: true,// 日期组件
		};
	},
	props:{
		elevatorId:{
			type:String,
			default:''
		}
	},
	mounted() {
		uni.getSystemInfo({
			success: (res) => {
				this.mheights = res.windowHeight - 78 - 240;
				// console.log(res,this.safeAreaBottom,666)
			},
		});
		this.fetchEleDetail();
		// 默认加载7个月数据
		this.startDate = dayjs(new Date().getTime() - 1000 * 60 * 60 * 24).subtract(2, 'month').format('YYYY-MM-DD');
		this.endDate = dayjs(new Date().getTime() - 1000 * 60 * 60 * 24).add(4, 'month').format('YYYY-MM-DD');
		this.initPlanDateData([this.elevatorId], this.startDate, this.endDate);
	}, 
	onShow() {
		// this.fetchOrderList();
	}, 
	methods:{
		// 查列表信息
		fetchOrderList() {
			uni.showLoading({
				title: '加载中',
				mask: true
			});
			
			// 这里是任务安排
			// 如果是保养
			const queList = [maintenanceUnfinished,];
			queList[this.tabIdx]({ elevatorId: this.elevatorId,type:this.tabIdx == 3 ? 1 : '' }).then(res => {
				uni.hideLoading();
				let title = res.data.title;
				if (this.tabIdx == 3) {
					title = '仅显示未完成的救援任务';
				}
				this.title = title;
				// this.list = res.data.list;
				const records = res.data.list || [];
				records.forEach((item, index) => {
					for (let i = 0; i < item.dataList.length; i++) {
						item.dataList[i].usermore = false;
						if (item.dataList[i].partsName != null) {
							const parts = item.dataList[i].partsName.split('&amp;&amp;');
							item.dataList[i].parts = parts[parts.length - 1];
						}
					}
				});
				this.list = records;
				// this.isCanScroll = this.list.length ? true : false
			});
		},
		// 获取电梯详情 及责任人
		fetchEleDetail() {
			elevtorDetail({ elevatorId: this.elevatorId }).then(res => {
				if (res) {
					this.eleMsg = res.data;
				}
			});
			elevtorMantles({ elevatorId: this.elevatorId }).then(res => {
				if (res) {
					this.mantles = res.data;
				}
			});
		},
		// 切换月历组件
		changeTypes(val) {
			this.typeIndex = val;
			// this.tabIdx = 0
			// this.tabIdxState = true 
			
			if (val === 1) {
				this.initPlanDateData([this.elevatorId], this.startDate, this.endDate);
			} else {
				this.fetchOrderList();
			}
		},
		//
		handleUserMore(res) {
			// console.log(res,666);
			// console.log(this.list,"list");
			const { parentIdx, childIdx, val } = res;
			try {
				this.list[parentIdx].dataList[childIdx].usermore = val;
			} catch (error) {
				
			}
		},
		// 
		restList() {
			this.list = [];
			this.title = '';
			this.fetchOrderList();
		},
		todayClick() {
			this.initPlanDateData([this.elevatorId], this.startDate, this.endDate);
		},
		// 初始加载日历排期数据
		initPlanDateData(elevatorIds = [], startDate, endDate, arrow) {
			uni.showLoading({
				title: '加载中',
				icon: 'none'
			});
			calendarPlan({
				elevatorIds,
				startDate,
				endDate
			}).then(res => {
				uni.hideLoading();
				if (res.code === 200) {
					this.monthArrs = res.data || {};
					this.$refs['monthPlanCom'].initDate(this.monthArrs, arrow);
				}
			}).catch(err => {
				uni.hideLoading();
			});
		},
		// 日历滚动加载数据
		loadScrollMonth(obj, count, arrow) {
			console.log('hahhggg', obj, count,);
			let startDate = dayjs(obj.year + '-' + (obj.month > 9 ? obj.month : '0' + obj.month)).format('YYYY-MM-DD');
			let endDate = dayjs(obj.year + '-' + (obj.month > 9 ? obj.month : '0' + obj.month)).add(4, 'month').format('YYYY-MM-DD');
			if (count === -1) {
				endDate = obj.year + '-' + (obj.month > 9 ? obj.month : '0' + obj.month) + '-' + '01';
				startDate = dayjs(obj.year + '-' + (obj.month > 9 ? obj.month : '0' + obj.month)).subtract(3, 'month').format('YYYY-MM-DD');
			}
			// if(inits > 1){
			this.initPlanDateData([this.elevatorId], startDate, endDate, arrow);
			// }
		},
		// 选择日历日期
		selectTime(item, year, month) {
			if (!item.planObj.elevatorCount) {
				uni.showToast({
					title: '该日期无保养计划',
					icon: 'none',
				});
				return;
			}
			this.$refs.listsCom.inits();
			let strTimes = year + '-' + (month > 9 ? month : '0' + month) + '-' + (item.date > 9 ? item.date : '0' + item.date);
			this.strTimes = strTimes.replace(/-/g, '/');
			// this.listModle(this.elevatorId, strTimes, strTimes)
		},
		// 月历计划单梯数据
		listModle(elevatorId, startTime, endTime) {
			getRepairCheck({
				elevatorId,
				startTime,
				endTime,
				current: 1,
				size: 10,

			}).then(res => {
				if (res.code === 200) {
					this.listComData = res.data.records || [];
				}
			});
		},
		// 电梯排期下载excel
		initElevatorExcel(elevatorIds, startDate, endDate, type) {
			uni.showLoading({
				title: '下载中',
				icon: 'none'
			});
			calendarPlanExcel({
				elevatorIds,
				startDate,
				endDate,
				type
			}).then(res => {
				console.log('calendarPlanExcel', res);
				this.successVisible = true;
				if (res.code === 200) {
					let excelURl = res.data;
					let str = excelURl.split('/')[excelURl.split('/').length - 1];
					this.excelURl = excelURl;
					// #ifdef h5
					uni.hideLoading();
					// #endif

					// #ifndef H5
					uni.downloadFile({
						url: res.data,
						filePath: wx.env.USER_DATA_PATH + '/' + str,
						success: (data) => {
							console.log(data, '下载的文件');
							if (data.statusCode === 200) {
								uni.hideLoading();
								// this.tempFilePath = data.tempFilePath;
								this.tempFilePath = data.filePath;
							}
						},
					});
					// #endif
				}
			});
		},
		openFile() {
			// #ifdef H5
			sida.openUrl({ url: this.excelURl });        
      		// #endif

			// #ifndef H5
			console.log(this.tempFilePath, 'this.tempFilePath');
			uni.openDocument({
				filePath: this.tempFilePath,
				showMenu: true,
				fileType: 'xlsx',
				success: (res) => {
					console.log('打开文档成功');
					this.successVisible = false;
				},
				fail: (err) => {
					console.log(err);
				}
			});
			// #endif
		},
		// 复制链接
		copyLink() {
			uni.setClipboardData({
				data: this.excelURl,
				success: (res) => {
					uni.getClipboardData({
						success(res) {
							console.log(res.data); // data
						},
					});
					this.successVisible = false;
				},
			});
		},
		// 自定义日期 --完成时间
		closeSelectTimePopup(res) {
			let start = '';
			let end = '';
			if (res) {
				console.log('自定义日期', res);
				if (res.indexOf('-') != -1) {
					const timeArr = res.split('-');
					start = timeArr[0].replaceAll('.', '-');
					end = timeArr[1].replaceAll('.', '-');
				} else {
					const time = res.replaceAll('.', '-');
					start = time;
					end = time;
				}
				const nowDay = getNowTime();
				let nowtime = new Date(nowDay).getTime();
				let starttime = new Date(start).getTime();
				let endtime = new Date(end).getTime();
				if (endtime >= nowtime && !this.beforeToday && !this.isChooseToday) {
					console.log('包含今天');
					uni.showToast({
						title: '自定义日期范围须小于今天',
						icon: 'none',
					});
					return;
				}
			}
			if (start && end) {
				this.curStartDate = start;
				this.curEndDate = end;
				uni.$emit('closeTimeSelectPlan', { start, end, value: '' });// 向兄弟组件回显日期
				let objs = { elevatorIds: [this.elevatorId], planBeginDate: this.curStartDate || '', planEndDate: this.curEndDate || '', cuValue: this.curValue || 3 };
				this.handleCount(objs);
			}
			this.selectTimePopup = false;
			// uni.$emit("closeTimeSelect", { start, end, optionKey: this.optionKey });
		},

		// 完成筛选
		filterdr(res) {
			console.log(res, 'his.choosed');

			let obj = JSON.parse(JSON.stringify(res.dateObj));
			if (obj.startTime && obj.startTime.indexOf(':') == -1) {
				obj.startTime = obj.startTime + ' 00:00:00';
			}
			if (obj.endTime && obj.endTime.indexOf(':') == -1) {
				obj.endTime = obj.endTime + ' 23:59:59';
			}

			if (obj.planBeginDate && obj.planBeginDate.indexOf(':') == -1) {
				obj.planBeginDate = obj.planBeginDate + ' 00:00:00';
			}
			if (obj.planEndDate && obj.planEndDate.indexOf(':') == -1) {
				obj.planEndDate = obj.planEndDate + ' 23:59:59';
			}
			let planBeginDate = '';
			let planEndDate = '';
			if (!obj.value2) {
				obj.value2 = 6;
				planBeginDate = res.dateObj.planBeginDate;
				planEndDate = res.dateObj.planEndDate;
			}
			this.initElevatorExcel([this.elevatorId], planBeginDate, planEndDate, obj.value2 - 1);
			this.initPlanDateData([this.elevatorId], this.startDate, this.endDate);
		},
		// 保存筛选
		submitFilter(res) {
			if (!this.countState) {
				return;
			}
			this.keyMap = res.keyMap;
			this.allChecked = res.allChecked;
			this.choosed = res.choosed;
			this.showFilter = false;
			// this.setChooseArr();
			this.filterdr(res);
			this.$refs['filter-drawer'].mianPlanReset({});// 初始
		},
		// 点击标签的时候
		getResultCount(res) {
			if (res.cuValue) {
				this.curValue = res.cuValue;
			}
			this.$nextTick(() => {
				if (res.choosed.useTypes && res.choosed.useTypes.length && res.hasOwnProperty('value')) {
					// this.$refs.groupSelect.initData() 
				} else {
					this.handleCount(res);
				}
			});
		},
		handleResetting() {
			this.comfireText = '确定0个计划';
			this.countState = 0;
			// this.$refs['groupSelect'].handleReset()
		},
		// 打开下载弹窗
		selectDown() {
			this.showFilter = true;
			this.curStartDate = '';
			this.curEndDate = '';
			let objs = {
				elevatorIds: [this.elevatorId],
				planBeginDate: this.startDate,
				planEndDate: this.endDate,
				cuValue: 3
			};
			this.handleCount(objs);
			this.$nextTick(() => {
				this.$refs['filter-drawer'].defaultPlan({ value: 3 });
			});
		},
		handleClose() {
			this.showFilter = false;
			let obj = {};
			this.chooseArr.forEach(item => {
				if (obj[item.key]) {
					obj[item.key].push(item.value);
				} else {
					obj[item.key] = [];
					obj[item.key].push(item.value);
				}
			});
			this.choosed = obj;
			// this.$refs['filter-drawer'].initData(obj)
		},
		// 弹窗后点击日期
		customerOpenTime(objs) {
			this.selectTimePopup = objs.isState;
		},
		// 重置默认
		defaultReset() {
			// this.selectArr = []
			// this.filterList[0].list[0].name = '全部电梯'
			this.$refs['filter-drawer'].defaultPlan({ value: 3 });
			let objs = { planBeginDate: '', planEndDate: '', cuValue: 3 };
			this.handleCount(objs);
		},
		// 获取点击筛选条件后的数量总数	
		async handleCount(res) {
			const { allChecked, choosed, reset, cuValue } = res;
			if (reset) {
				this.handleResetting();
				return;
			}
			if (!cuValue) {
				this.comfireText = '确定0个计划';
				this.countState = 0;
				return;
			}
			let params = {
				elevatorIds: [this.elevatorId],
				startDate: res.planBeginDate,
				endDate: res.planEndDate,
				type: res.cuValue - 1 || 0,// 日期选择的类型
			};
			if (Object.keys(res).length) {
				// let resultObjs = removeEmpty(params)
				let count = await this.handleGetCount(params);
				this.countState = count;
				if (count > 0) {
					this.comfireText = `确定${count}个计划`;
				} else {
					uni.showToast({
						icon: 'none',
						title: '筛选结果为空 请重新选择条件'
					});
					this.countState = 0;
					this.comfireText = '确定0个计划';
				}
			}
		},
		// 获取计划数量
		handleGetCount(objs) {
			return new Promise((resolve, reject) => {
				calendarStatisticsCount(objs).then(res => {
					if (res.code === 200) {
						let arrs = res.data || [];
						resolve(arrs);
					}
				});
			}).catch((err) => reject([]));
		},
	}
};
</script>
<style>
page {
	background-color: #f6f5f8;
}
</style>
<style lang="scss" scoped>

.todayPlus {
	position: relative;
}
.today {
	font-size: 26rpx;
	color: #666666;
	position: absolute;
	right: 30rpx;
	top: 12rpx;

	text:nth-of-type(1) {
		color: #333333;
		vertical-align: middle;
	}

	image {
		width: 32rpx;
		height: 32rpx;
		margin-right: 4rpx;
		margin-left: 5rpx;
		vertical-align: middle;
	}
}
.text_tit{
	display: flex;
	// justify-content: center;
	margin: 16rpx;
	color: #666666;
	font-size: 26rpx;

}
.tabBox {

    .typeTag {
        display: flex;
        background-color: #fff;
        padding: 20rpx 0 0rpx 0;

        .typeTag_item {
            display: flex;
            flex: 1;
            justify-content: center;
            align-items: center;
            height: 44rpx;
            color: #999;
            font-size: 32rpx;

            image {
                width: 28rpx;
                height: 28rpx;
                margin-top: 16rpx;
            }
        }

        .typeTag_item:nth-child(1) {
            border-right: 2rpx solid #ccc;
        }

        .active {
            color: #333;
            font-weight: 600;
        }

        .tipStyle {
            padding: 0 16rpx;
            // background: pink;
        }
    }

    .tabs {
        // width: 96%;
        // padding: 0 2%;
        background-color: #ffffff;
        display: flex;
        //    position: sticky;
        // z-index: 99999;
        border-bottom: 2rpx #eee solid;

        &-item {
            height: 84rpx;
            line-height: 83rpx;
            margin: 0 20rpx;
            font-size: 26rpx;
            font-weight: 400;
            border-bottom: 4rpx solid #fff;
            color: #93b1c7;
            transition: 0.4s all;
        }

        .act {
            color: #0091ff;
            // font-weight: bold;
            // height: 60rpx;
            // box-sizing: border-box;
            // padding: 16rpx 20rpx;
            border-color: #0091ff;
            font-size: 30rpx;
        }
    }

}
.orderTips {
    font-size: 26rpx;
    color: #666;
    text-align: center;
    // margin: 20rpx 0;
    padding: 20rpx 0;
}
.orderListMain {

.content_Tit {
    display: flex;
    justify-content: space-between;

    .date_count {
        font-size: 24rpx;
        color: #666666;
        margin-right: 20rpx;

        text {
            color: #0091FF;
        }
    }
}

.date {
    color: #333;
    font-size: 26rpx;
    font-weight: 600;
    padding-left: 40rpx;
    position: relative;
}

.line {
    width: 4rpx;
    height: 22rpx;
    background: #333333;
    position: absolute;
    left: 20rpx;
    top: 8rpx;
}

.more {
    width: 100%;
    padding: 30rpx 0;
    text-align: center;
    color: #999999;
    font-size: 24rpx;
}
}
.empty {
    display: flex;
    align-items: center;
    justify-content: center;

    image {
        width: 64rpx;
        height: 64rpx;
    }

    height: 800rpx;
    flex-direction: column;
}

.tabMonth {
	background: #fff;
	display: flex;
	justify-content: center;
	padding: 20rpx 0;
	align-items: center;
	position: relative;

	.tabMonth_M {}

	.filterBox {
		display: flex;
		font-size: 24rpx;
		color: #666;

		.typeItem {
			// width: 112rpx;
			height: 56rpx;
			border: 2rpx solid #d5d5d5;
			display: flex;
			padding-right: 10rpx;
			align-items: center;
			justify-content: center;
			vertical-align: middle;
			transition: .3s all;

			.ico {
				width: 28rpx;
				height: 28rpx;
				padding: 0 10rpx;
			}
		}

		.typeItem:nth-child(1) {
			border-radius: 28rpx 0rpx 0rpx 28rpx;
		}

		.typeItem:nth-child(2) {
			border-radius: 0rpx 28rpx 28rpx 0rpx;
			border-left: none;
		}

		.act {
			background: #dcf0ff;
			border-color: #0091ff;
			color: #0091ff;
		}

		.actRight {
			border-left: 2rpx solid !important;
		}
	}

	.tab_down {
		font-size: 26rpx;
		color: #666;
		position: absolute;
		right: 20rpx;

		image {
			vertical-align: middle;
			margin-right: 10rpx;
		}

		text {
			vertical-align: middle;
		}
	}

}

</style>